﻿using System;
using System.Configuration;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web.Script.Serialization;

namespace ZenHR.AttData.Package.Util
{
 public static class Utility
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetConfig(string key)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            //make changes
            return config.AppSettings.Settings[key].Value;
        }

        public static string UrlEncode(string str)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
            }

            return (sb.ToString());
        }

        /// <summary>
        /// 将Json字符串序列化成对象
        /// </summary>
        /// <typeparam name="T">目标对象泛型</typeparam>
        /// <param name="JsonStr">json 字符串</param>
        /// <returns></returns>
        public static T JSONStringToList<T>(string JsonStr)
        {
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            Serializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
            var objs = Serializer.Deserialize<T>(JsonStr);
            return objs;
        }

        /// <summary>
        /// OBJ TO JSON STRING
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToJson(object obj)
        {
            var serializer = new DataContractJsonSerializer(obj.GetType());
            var stream = new MemoryStream();
            serializer.WriteObject(stream, obj);
            var dataBytes = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(dataBytes, 0, (int)stream.Length);
            return Encoding.UTF8.GetString(dataBytes);
        }

        public static string ToJSONStringFromObject(this object o)
        {
            if (o == null)

            {
                return null;

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(o);

        }

    }
}
